package connect

import (
	"litetalk/proto"
	"sync"
)

type Bucket struct {
	lock sync.RWMutex
	chs  map[uint]*Channel
}

func NewBucket() *Bucket {
	return &Bucket{
		chs: make(map[uint]*Channel),
	}
}

func (b *Bucket) Put(userId uint, ch *Channel) {
	b.lock.Lock()
	ch.userId = userId
	b.chs[userId] = ch
	b.lock.Unlock()
}

func (b *Bucket) DeleteChannel(ch *Channel) {
	b.lock.Lock()

	var ok bool
	if ch, ok = b.chs[ch.userId]; ok {
		delete(b.chs, ch.userId)
	}
	b.lock.Unlock()
}

func (b *Bucket) OnlineCount() (cnt int) {
	b.lock.RLock()
	cnt = len(b.chs)
	b.lock.RUnlock()
	return
}

func (b *Bucket) Channel(userId uint) (ch *Channel) {
	b.lock.RLock()
	ch = b.chs[userId]
	b.lock.RUnlock()
	return
}

func (b *Bucket) Broadcast(msg *proto.Msg, FromUserId uint) {
	for _, v := range b.chs {
		if v.userId != FromUserId {
			v.PushMsg(msg)
		}
	}
}

func (b *Bucket) GetOnlineUser(res *proto.IMOnlineUserRes) {
	b.lock.RLock()
	for _, v := range b.chs {
		res.UserIdList = append(res.UserIdList, v.userId)
	}
	b.lock.RUnlock()
}
